<?php
/**
 * 菜单控制器
 * Enter description here ...
 * @author Administrator
 *
 */
namespace System\Controller;
use Common\Controller\TreeController;
use Common\Controller\BaseController;
class SysMenuController extends BaseController{
	const modelName = CONTROLLER_NAME;
	
	protected function _initialize(){
		parent::_initialize();
		
		$this->checkAuth();
		
		$this->model = D(self::modelName);
	}
	
	
	/**
	 * 列表
	 * Enter description here ...
	 */
	public function index(){
        if(IS_AJAX){
            //条件查询
            $name = I('get.name');
            $name && $map['name'] = array('like','%'.$name.'%');

            //获取列表
            $map['is_hidden'] = 0;
            $field = 'pk_id,name,IF(pid=0,"顶级菜单",(SELECT name FROM sys_menu AS m WHERE m.pk_id = sys_menu.pid)) AS fk_mod_id,create_time';
            $data = $this->getRows(self::modelName, $map ,$field ,1 ,I('get.order'));
            $this->data = $data;
            $this->rtnResult(0);
        }else{
            //表头、字段名
            $data['field'] = 'pk_id,name,fk_mod_id,create_time';
            $data['titleArr'] = array('编号','菜单名','所属模块','添加时间');
            $this->showView($data,'./Public/Admin/Tpl/index.html');
        }
	}
	
	
	/**
	 * 添加
	 * Enter description here ...
	 */
	public function add(){
		if (IS_POST){
			//添加菜单
			$this->model->startTrans();
			$menuid = $this->addData($this->model);
			
			if (empty($menuid)){
				$mark = 1;
			}else {
				//添加操作
				$opreat = I('post.access');
				if (!empty($opreat) && is_array($opreat)){
					$opreatModel = M('SysAccess');
					foreach ($opreat as $value){
						$info = $this->getOpreatInfo($value);
						$info['fk_menu_id'] = $menuid;
						if ($info){
							$this->addData($opreatModel,'','',$info,1);
						}
					}
				}
                //自动创建菜单类
                if(I('auto_create_class') == 'on'){
                    $this->createMenuClass(I('name'),I('control'),$opreat);
                }
                //自动生成视图目录
                if(I('auto_create_view_folder') == 'on'){
                    $control = I('control');
                    $access = I('access');
                    $control_arr = explode('/',$control);
                    $controller_name = $control_arr[1];
                    if($controller_name){
                        $folder_path = APP_PATH.$control_arr[0].'/View/'.$controller_name.'/';
                        if(!file_exists($folder_path)){
                            if(mkdir($folder_path)){
                                copy('./Public/Admin/tpl/index.html',$folder_path.'index.html');
                                if(in_array('add',$access)){
                                    copy('./Public/Admin/tpl/add.html',$folder_path.'add.html');
                                }
                                if(in_array('edit',$access)){
                                    copy('./Public/Admin/tpl/edit.html',$folder_path.'edit.html');
                                }
                            }
                        }
                    }
                }
			}

			//保存操作ID
			$this->transReturn($this->model, $mark ,'保存成功|保存失败','index');
		}else {
			//获取菜单列表
			$map['is_del'] = 0;
			$field = 'pk_id,pid,name';
			$list = $this->getRows(self::modelName,'',$field);
			$menuTree = new TreeController();
			$data['menu_rows'] = $menuTree->toFormatTree($list);
			
			//系统可用操作
			$field = 'pk_id,name,action';
			$data['action'] = $this->getRows('SysAction', array('type'=>1),$field,'pk_id ASC');
			
			//显示视图
			$this->showView($data);
		}
	}
	
	
	/**
	 * 修改
	 * Enter description here ...
	 */
	public function edit(){
		if (IS_POST){
			//修改菜单
			$this->model->startTrans();
			$this->editData($this->model);
			
			//修改操作
			$new_opreat = I('post.access');
            empty($new_opreat) && $new_opreat = array();
			if (is_array($new_opreat)){
				$opreatModel = M('sys_access');
				
				//当前可用操作
				$id = I('pk_id');
				$old_opreat = $opreatModel->where('fk_menu_id = %d AND status = 0',$id)->getField('access',true);
				empty($old_opreat) && $old_opreat = array();
				
				//删除交集以外的数据
				$intersect = array_intersect($new_opreat,$old_opreat);
				if (!empty($intersect)){
                    $map['access'] = array('NOT IN',$intersect);
				}
                $map['fk_menu_id'] = $id;
                if ($opreatModel->where($map)->setField('status',1) === false){
                    $mark = 1;
                }
				
				//添加差集的数据
				$diff = array_diff($new_opreat,$old_opreat);
				if (!empty($diff)){
					foreach ($diff as $value){
						//是否已在未删除行列
						$aid = $opreatModel->where("access = '%s' AND fk_menu_id = %d",$value,$id)->getField('pk_id');
						if ($aid){
							$opreatModel->where("access = '%s' AND fk_menu_id = %d",$value,$id)->setField('status',0);
						}else {
							//生成数据
							$info = $this->getOpreatInfo($value);
							$info['fk_menu_id'] = $id;
							if ($info){
								$aaa = $opreatModel->add($info);
							}
						}
					}
				}
			}
			
			//保存操作ID 
			$this->transReturn($this->model, $mark , '保存成功|保存失败','index');
		}else {
			//获取菜单列表
			$field = 'pk_id,pid,name';
			$list = $this->getRows(self::modelName,'',$field);
			$menuTree = new TreeController();
			$data['menu_rows'] = $menuTree->toFormatTree($list);
			
			//当前菜单信息
			$id = I('pk_id');
			$data['menu'] = $this->model->where('pk_id = %d',$id)->find();
			
			//系统可用操作
			$field = 'pk_id,name,action';
			$data['action'] = $this->getRows('SysAction', array('type'=>1),$field);

			//当前菜单可执行操作
			$map['fk_menu_id'] = $id;
			$map['status'] = 0;
			$data['access_op'] = M('SysAccess')->where($map)->getField('access',true);

			//显示视图
			$this->showView($data);
		}
	}

    /**
     * 删除数据
     * POST请求为批删，GET请求为删除单条
     */
    public function del(){
        $this->delData($this->model,'删除成功|删除失败|ajax');
    }

    /**
     * 获取操作信息
     * @param string $action 操作
     * @return mixed
     */
	protected function getOpreatInfo($action=''){
		$info = M('SysAction')->where("action = '%s'",$action)->field('name,action AS access')->find();
		return $info;
	}

    /**
     * 创建菜单类
     */
    protected function createMenuClass($class_title,$url,$access){
        $url_info = explode('/',$url);
        $module_name = $url_info[0];
        $class_name = $url_info[1]; //类名
        $class_file_name = $class_name.'Controller.class.php'; //类文件名
        $root = APP_PATH.$module_name.'/Controller/';
        $path = APP_PATH.$module_name.'/Controller/'.$class_file_name;
        $lists_fun = <<<str
    /**
     * 列表
     */
    public function index(){
        if(IS_AJAX){
            //获取列表
            \$this->create_condition(\$map);
            \$field = 'pk_id,create_time';
            \$this->data = \$this->getRows(self::modelName, \$map ,\$field ,1);
            \$this->rtnResult(0);
        }else{
            //表头、字段名
            \$data['field'] = 'pk_id,create_time';
            \$data['titleArr'] = array('编号','创建时间');
            \$this->showView(\$data,'./Public/Admin/Tpl/index.html');
        }
    }
str;

        if(in_array('edit',$access)){
            $edit_fun = <<<str
    /**
     * 编辑数据
     */
    public function edit(){
        if (IS_POST){
            \$this->editData(\$this->model,'修改成功|修改失败','index');
        }else {
            //获取详细信息
            \$map['pk_id'] = I('pk_id');
            \$data['info'] = \$this->getDataInfo(\$this->model, \$map);

            //获取角色列表
            \$this->showView(\$data);
        }
    }
str;
        }


        if(in_array('excel',$access)){
            $excel_fun = <<<str
    /**
     * 导出表格
     * Enter description here ...
     */
    public function excel(){
        //排序
        \$order = I('get.order');

        //系统调用则直接返回数组
        \$field = 'pk_id,create_time';
        \$rows = \$this->getRows(self::modelName, \$map ,\$field ,\$order);
        if (empty(\$rows)){
            \$this->error('暂无数据');
        }else{
            load('Common.exportxls');
            \$Columns=array(
                array('name'=>'编号','value'=>'pk_id'),
                array('name'=>'创建时间','value'=>'create_time'),
            );
            exportData(\$rows, \$Columns, '{$class_title}');
        }
    }
str;
        }


        //开始创建
        if(!file_exists($path)){
            $file_content = <<<str
<?php
namespace {$module_name}\Controller;
use Common\Controller\BaseController;
/**
 * $class_title
 * Class {$class_name}Controller
 * @package {$module_name}\Controller
 */
class {$class_name}Controller extends BaseController{
    const modelName = CONTROLLER_NAME;
    protected function _initialize(){
        parent::_initialize();
        \$this->checkAuth();
        \$this->model = D(self::modelName);
    }

$lists_fun

{$edit_fun}

{$excel_fun}

}
?>

str;

            writeToFile($file_content,$root,$class_file_name,'a+b');
        }
    }
}

?>